package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.WorkSpaceMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    ReportMapper reportMapper;

    @Autowired
    WorkSpaceMapper workSpaceMapper;

    @Autowired
    WorkSpaceService workSpaceService;


    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        //获取当天时间的最小值
        LocalDateTime beginLocalDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        //获取当天时间的最大值
        LocalDateTime endLocalDateTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOS = reportMapper.selectByTime(beginLocalDateTime, endLocalDateTime);

        String nameList = StringUtils.join(goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        salesTop10ReportVO.setNameList(nameList);
        salesTop10ReportVO.setNumberList(numberList);

        return salesTop10ReportVO;
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //查询当天的总用户数
            Integer totalUsers = reportMapper.countUsers(null, endTime);
            totalUserList.add(totalUsers);
            Integer increaseUsers = reportMapper.countUsers(beginTime, endTime);
            newUserList.add(increaseUsers);

        }
        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(StringUtils.join(dateList, ","));
        userReportVO.setNewUserList(StringUtils.join(newUserList, ","));
        userReportVO.setTotalUserList(StringUtils.join(totalUserList, ","));
        return userReportVO;
    }

    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            //查询当天的完成的订单的总金额
            Double totalAmount = reportMapper.countAmount(beginTime, endTime);
          totalAmount=  totalAmount == null ? 0.0:totalAmount;
            turnoverList.add(totalAmount);

        }

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(StringUtils.join(dateList, ","));
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));

        return turnoverReportVO;
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        List<Integer> statusList = List.of(2, 3, 4, 5);
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Integer orderCount = reportMapper.countTodayOrders(beginTime, endTime);
            orderCountList.add(orderCount);

            Integer validOrder = reportMapper.CountvalidOrder(beginTime, endTime, statusList);
            validOrderCountList.add(validOrder);

        }
        Integer validOrderCount = workSpaceMapper.getActiveOrdersNumber(null,null);
        Integer totalOrderCount = workSpaceMapper.selectAllOrdersCount();
        //转成double类型
        Double dValidOrderCount = Double.valueOf(validOrderCount);
        Double dTotalOrderCount = Double.valueOf(totalOrderCount);
        Double orderCompletionRate = 0.0;
        if (dTotalOrderCount != 0) {
            orderCompletionRate = dValidOrderCount / dTotalOrderCount;
        }

        OrderReportVO orderReportVO = new OrderReportVO();
        orderReportVO.setDateList(StringUtils.join(dateList, ","));
        orderReportVO.setOrderCountList(StringUtils.join(orderCountList, ","));
        orderReportVO.setValidOrderCountList(StringUtils.join(validOrderCountList, ","));
        orderReportVO.setOrderCompletionRate(orderCompletionRate);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        return orderReportVO;

    }

    /**
     * 将数据以excel表的形式导出
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) throws FileNotFoundException {
        //导出近30天的营业数据
        LocalDate startDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);

        //从数据库中查询近30天的数据
        BusinessDataVO businessDataVO = workSpaceService.businessData(LocalDateTime.of(startDate,LocalTime.MIN),LocalDateTime.of(endDate,LocalTime.MAX));


        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //概览数据
            sheet.getRow(1).getCell(1).setCellValue("时间："+startDate+"至"+endDate);
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

           row = sheet.getRow(4);
           row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
           row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

           //明细数据

            for (int i = 0; i < 30; i++) {

                LocalDate date = startDate.plusDays(i);
                BusinessDataVO businessDataVO1 = workSpaceService.businessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row = sheet.getRow(7 + i);
                 row.getCell(1).setCellValue(date.toString());
                 row.getCell(2).setCellValue(businessDataVO1.getTurnover());
                 row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
                 row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
                 row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
                 row.getCell(6).setCellValue(businessDataVO1.getNewUsers());

            }


           //将excel数据表响应给浏览器端,浏览器就会出现下载excel的提示框
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //释放资源
            out.close();
            excel.close();
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
